package com.oe.market.modules.cq.controller;


import com.google.gson.Gson;
import com.oe.market.modules.base.model.bean.RetResponse;
import com.oe.market.modules.cq.model.dao.CQMessageDao;
import com.oe.market.modules.cq.model.dto.CQPostMessageDto;
import com.oe.market.modules.cq.model.mapper.CQMessageMapper;
import com.oe.market.modules.cq.service.CQMessageAnalyzeService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;

@RestController
@RequestMapping(value = "/cq/")
@ResponseBody
public class CQHomeController {

    @RequestMapping(value = "/message")
    public String message(@RequestBody String body, HttpServletRequest request) {
        Gson gson = new Gson();
        // 结构化消息类型
        try {
            CQPostMessageDto privateMessageDto = gson.fromJson(body, CQPostMessageDto.class);
            String msg = CQMessageAnalyzeService.me.analyze(privateMessageDto.message);
            if (msg != null) {
                privateMessageDto.message = msg;
            }
            CQMessageMapper cqMessageMapper = new CQMessageMapper(privateMessageDto,new BigInteger(request.getHeader("X-Self-ID")));
            CQMessageDao.me.append(cqMessageMapper.getCqMessage());
        }
        catch (Exception e) {
            return RetResponse.failed().toString();
        }
        return RetResponse.success().toString();
    }
}
